from django.shortcuts import render, HttpResponse, redirect


# Create your views here.

# def 函数名(request):
#     return 响应

# def index(request):
#     print(request.method)
#     # return HttpResponse('hello world')
#     res = HttpResponse('hh')
#     res['hh'] = 'test'
#     return res

# 渲染

def index(request):
    # return render(request, 'app1/index.html', context={'var': '小明','people':'莘莘学子'}, status=200)
    return render(request, 'app1/index.html', {'var': '小明', 'people': '莘莘学子'})


class StudentB:
    def __init__(self, name, age, school):
        self.name = name
        self.age = age
        self.school = school


def show_obj(request):
    student = StudentB('张三', 12, '清华')

    return render(request, 'app1/show_dict.html', {'student': student}
                  )


def show_dict(request):
    student = {'name': 'rose',
               'age': 16,
               'school': 'zt'
               }

    return render(request, 'app1/show_dict.html', {'student': student}
                  )


def show_list(request):
    student = ['杰克', 18, 'tz']
    return render(request, 'app1/show_list.html', {'student': student}
                  )


# 注释

def show_list_for(request):
    student = ['杰克', 18, 'tz']
    return render(request, 'app1/show_list_for.html', {'student': student}
                  )


def show_if(request):
    student = ['杰克', 17, 'tz']
    return render(request, 'app1/show_if.html', {'student': student}
                  )


def show_if1(request):
    student = {'name': 'rose',
               'age': 16,
               'school': 'zt'
               }
    return render(request, 'app1/show_if1.html', {'student': student}
                  )


# 在模板中展示三个学生的信息,for
# 判断一下 学生是否成年   for中有if
def show_students(request):
    s1 = StudentB('张三', 18, 'zt')
    s2 = StudentB('李四', 16, '清华')
    s3 = StudentB('王五', 20, '北大')
    students = [s1, s2, s3]
    return render(request, 'app1/show_students.html', {'students': students})


def show_img(request):
    return render(request, 'show_img.html')


def show_filter(request):
    return render(request, 'show_filter.html', {'wd': "roSe blise", 'age': 2})


from .models import Student as Stu


# from app1.models import Student as Stu


def fun1(request):
    s1 = Stu(name='张三', age=12, introduce="巴拉巴拉ghjhj")
    s1.save()
    return HttpResponse('插入数据成功了')


def jump(request):
    return render(request, 'jump.html')


# ----------------------如何将url中的有效信息传递给后台(视图函数)----------------------------------
# 视图函数如何获取 url 路径中的变量
def book(request, bookid):
    return HttpResponse('你想查看的书的id是:{}'.format(bookid))


def book1(request, bookname):
    return HttpResponse("书名是{}".format(bookname))


def blog(request, authorname, blogid):
    return HttpResponse("authorname是{},blogid是{}".format(authorname, blogid))


def book2(request, bookname):
    print(request.method)  # GET
    return HttpResponse("书名是{}".format(bookname))


# http协议的封装  请求信息--> request
# 如何获取url参数
def book3(request):
    id = request.GET.get('id')
    return HttpResponse("书的 id是{}".format(id))


def baidu(request):
    ie = request.GET.get('ie', 'no')
    wd = request.GET.get('wd', '')
    return HttpResponse('ie={}&wd={}'.format(ie, wd))


# 如何区分 get请求 和post请求
# 如何获取post请求传过来的数据
def register(request):
    if request.method == "GET":
        return render(request, 'register.html')
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        return HttpResponse('传递过来的用户名;{},传递过来的密码:{}'.format(username, password))


from .models import Student


def stu_add(request):
    if request.method == "GET":
        return render(request, 'stu_add.html')
    if request.method == "POST":
        # 获取表单中  post过来的数据
        name = request.POST.get('name')
        age = request.POST.get('age')
        introduce = request.POST.get('introduce')

        # 创建一个模型
        # s = Student(name=name, age=age, introduce=introduce)
        # s.save()

        Student.objects.create(name=name, age=age, introduce=introduce)

        return HttpResponse('插入成功')


def query_stu_one(request):
    """
    查询单个学生信息
    :param request:
    :return:
    """
    # 只能查找一个
    # 没有找到 就报错,
    # 结果多余1个,也报错
    # 返回值 一个模型对象
    stu = Student.objects.get(name='rose')
    print(stu)
    print(type(stu))
    return HttpResponse(stu.name)


from django.db.models import Q


def query_stu_m(request):
    """
    filter 查询结果是一个 容器类型 QuerySet
    你可以把它理解成list
    :param request:
    :return:
    """
    # stus = Student.objects.filter(name='rose')
    # stus = Student.objects.filter(id=79)
    # stus = Student.objects.all()  # QuerySet
    # stus = Student.objects.filter(introduce__contains="泰坦尼克")
    # ignore 忽略大小写
    # stus = Student.objects.filter(name__icontains='ROSE')  # 名字中包含某个字符串的
    # 更加复杂的查询方式
    #  名字是rose  并且 age=15
    #  gt ==>greater than 大于
    # lt less than  小于   e ==> equal 等于
    # stus=Student.objects.filter(name='rose').filter(age__gt=15)
    stus = Student.objects.filter(name='rose').filter(age__gte=15)
    # queryset 可以链式查询
    # & 并且
    # ~除了
    # | 或者
    # sqlite 默认配置只支持不区分大小写的ASCII码比较
    # stus = Student.objects.filter(Q(name__contains='ro') & Q(age__gte=15))
    # stus = Student.objects.filter(Q(name__contains='ro') | Q(age=27))
    # stus = Student.objects.filter(Q(name__contains='ro') & ~Q(age=15),name='张三')
    stus = Student.objects.filter(Q(name__contains='ro') & ~Q(age=15))

    print(stus)
    print(type(stus))  # <class 'django.db.models.query.QuerySet'>
    # QuerySet 像list一样的鸭子
    if stus:
        print(stus.first().name)
        print(stus[0].name)

        print(stus.last().name)
        print(stus[len(stus) - 1].name)

    return HttpResponse('查询成功')


# 1 有界面
# 2 搜索
# 3 后台 接收传过来的值
# 4 去数据库里查
# 5 查到了  返回给前端

def query_stu(request):
    wd = request.GET.get('wd', '')
    print(type(wd))
    if wd:
        if wd.isdigit():
            # students = Student.objects.filter(Q(age=int(wd)) | Q(name__icontains=wd))
            students = Student.objects.filter(age=int(wd))
        else:
            students = Student.objects.filter(name__icontains=wd)
    else:  # 默认情况  展示所有数据
        students = Student.objects.all()
    return render(request, 'query_stu.html', {"students": students})


def del_stu2(request):
    pass


def del_stu(request, stu_id):
    """
    删除功能没有界面
    :param request:
    :param stu_id:
    :return:
    """
    try:
        Student.objects.get(id=stu_id).delete()
    except:
        return HttpResponse('没有这条数据')

    # return HttpResponse('删除成功')
    # 重定向
    return redirect('app1:query_stu')


def update_stu(request, stu_id):
    """
    更新是在查询的基础上的
    展示数据的时候,将数据展示在表单中
    区分 get请求和post请求
    :param request:
    :param stu_id:
    :return:
    """
    student = Student.objects.get(id=stu_id)
    if request.method == "GET":
        return render(request, 'update_stu.html', {"student": student})
    if request.method == "POST":
        name = request.POST.get('name')
        age = request.POST.get('age')
        introduce = request.POST.get('introduce')

        student.name = name
        student.age = age
        student.introduce = introduce
        student.save()  # 不要忘
        return HttpResponse('修改成功!')
